<template>
  <t-dialog
    v-model:visible="show"
    :width="850"
    :footer="false"
    destroyOnClose
    :closeOnOverlayClick="false"
    placement="center"
  >
    <template #body>
      <t-tabs v-model="template.tab" @change="onPDFView">
        <t-tab-panel 
          v-for="(item, index) in template.list"
          :value="index" 
          :label="item.name"
        />
      </t-tabs>
      <t-loading :loading="loading">
        <Pdfview ref="pdfview" style="height: 900px" @load="loading = true" @over="loading = false" />
      </t-loading>
    </template>
    <template #header>
      {{ $t('common.view') }}
      <t-button theme="success" size="small" style="margin-left: 20px" @click="onDown">
        <template #icon>
          <t-icon name="download" size="16" style="margin-right: 0" />
        </template>
        {{ $t('common.pdf')  }}
      </t-button>
    </template>
  </t-dialog>
</template>
<script setup>
  import { ref, reactive, nextTick } from 'vue'
  import app from '@/app'

  import templateStore from '@/plugin/config/store/template'
  import Pdfview from '@/components/pdfview.vue'

  const show = ref(false)
  const loading = ref(false)
  const pdfview = ref()
  const template = reactive({
    list: [],
    data: {},
    tab: 0,
    keyword: '',
    down: ''
  })

  const open = async(data) => {
    // 模版名
    template.keyword = data.type
    // 模型列表
    template.list = templateStore.keyword(template.keyword)
    // 下载名
    template.down = data.number
    // 数据
    template.data = data
    // 默认显示的模版index
    template.tab = 0
    
    if(!template.list.length) {
      return app.message('warning', 'message.error.template')
    }

    // 显示窗体
    show.value = true
    await nextTick()
    
    // 显示模版
    onPDFView()
  }

  const onPDFView = async() => {
    // 使用模版
    const data = templateStore.make(template.keyword, template.tab)

    // 生成视图
    const build = await templateStore.build(data.view, template.data.data, data.data)

    // 放入二维码
    build.content.push({
      svg: '<svg width="300" height="220" viewBox="0 0 300 220"></svg>'
    }, {
      alignment: 'right',
      absolutePosition: { x: 100, y: 630 },
      stack: [{
        text: template.data.tbai,
        fontSize: 10,
        bold: true
      }, {
        margin: [0, 10, 0, 0],
        qr: template.data.url,
        fit: 150
      }]
    })

    // 创建pdf
    pdfview.value.create(build)
  }

  const onDown = () => {
    pdfview.value.down(template.down)
  }

  // 更新配置
  templateStore.get()

  defineExpose({ open })
</script>